package sample.springframework_practice.dao.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.util.Assert;

import sample.springframework_practice.dao.MessageDao;
import sample.springframework_practice.entity.Message;

public class MessageDaoImpl extends JdbcDaoSupport implements MessageDao {

    @Autowired
    public MessageDaoImpl(DataSource dataSource) {
	setDataSource(dataSource);
    }

    @Override
    public List<Message> selectMessageByRange(long start, long end) {
	final String sql = "SELECT number, title, body, author, modified, posted FROM ( SELECT ROW_NUMBER() OVER () AS R, number, title, body, author, modified, posted FROM message ORDER BY posted DESC ) AS T WHERE T.R BETWEEN ? AND ?";
	return getJdbcTemplate().query(sql, new BeanPropertyRowMapper<Message>(Message.class), start, end);
    }

    @Override
    public int insertMessage(Message message) {
	Assert.notNull(message);
	final String sql = "INSERT INTO message(number, title, body, author, modified, posted) VALUES (?, ?, ?, ?, ?, ?)";
	return getJdbcTemplate().update(sql,
		message.getNumber(),
		message.getTitle(),
		message.getBody(),
		message.getAuthor(),
		message.getModified(),
		message.getPosted()
	);
    }

    @Override
    public int updateMessage(Message message) {
	Assert.notNull(message);
	final String sql = "UPDATE message SET title = ?, body = ?, author = ?, modified = ?, posted = ? WHERE number = ?";
	return getJdbcTemplate().update(sql,
		message.getTitle(),
		message.getBody(),
		message.getAuthor(),
		message.getModified(),
		message.getPosted(),
		message.getNumber()
	);
    }
}
